﻿using System.Buffers.Binary;
using System.IO;
using System.IO.Compression;

namespace TiffLibrary.Tests
{
    internal class Deflate
    {

        public static byte[] Encode(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream();
            ms.Write(new byte[4], 0, 4);
            using (DeflateStream deflate = new DeflateStream(ms, CompressionLevel.Optimal))
            {
                deflate.Write(buffer, 0, buffer.Length);
            }
            byte[] result = ms.ToArray();
            BinaryPrimitives.WriteInt32LittleEndian(result, buffer.Length);
            return result;
        }

        public static byte[] Decode(byte[] buffer)
        {
            int length = BinaryPrimitives.ReadInt32LittleEndian(buffer);
            byte[] result = new byte[length];
            MemoryStream ms = new MemoryStream(buffer, 4, buffer.Length - 4);
            using (DeflateStream deflate = new DeflateStream(ms, CompressionMode.Decompress))
            {
                deflate.Read(result, 0, length);
            }
            return result;
        }
    }
}
